import socketserver
from http.server import SimpleHTTPRequestHandler
from urllib.parse import parse_qs
from urllib.parse import urlparse

PORT = 8000

conditionFilePath = "bookCondition_{}.json"
useListFilePath = "use_bookList_{}.json"
useBookFilePath = "use_{}/bookDetail_{}_{}.json";
badResponse = "{\"code\":301,\"msg\":\"数据不存在\"}"

class handler(SimpleHTTPRequestHandler):

    def do_GET(self):
        o = urlparse(self.path)
        if o.path.startswith("/resource"):
            super(handler, self).do_GET()
            return
        else:
            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self.end_headers()
            if o.path == "/book/condition":
                try:
                    bookTypeId = parse_qs(o.query)["bookTypeId"][0]
                    listFile = open(conditionFilePath.format(bookTypeId))
                    self.wfile.write(listFile.read().encode(encoding='utf-8'))
                    listFile.close()
                except BaseException:
                    self.wfile.write(badResponse.encode(encoding='utf-8'))
                return
            if o.path == "/book/list":
                try:
                    bookTypeId = parse_qs(o.query)["bookTypeId"][0]
                    listFile = open(useListFilePath.format(bookTypeId))
                    self.wfile.write(listFile.read().encode(encoding='utf-8'))
                    listFile.close()
                except BaseException:
                    self.wfile.write(badResponse.encode(encoding='utf-8'))
                return
            if o.path == "/book/bookDetail":
                try:
                    bookTypeId = parse_qs(o.query)["bookTypeId"][0]
                    bookId = parse_qs(o.query)["bookId"][0]
                    publishingId = parse_qs(o.query)["publishingId"][0]
                    detailFile = open(useBookFilePath.format(bookTypeId, publishingId, bookId))
                    self.wfile.write(detailFile.read().encode(encoding='utf-8'))
                    detailFile.close()
                except BaseException:
                    self.wfile.write(badResponse.encode(encoding='utf-8'))
                return

with socketserver.TCPServer(("", PORT), handler) as httpd:
    httpd.serve_forever()
